<?php
include("config/session.php");
include("./config/config.inc.php");
include("./config/QuickMySQL.php");
include("./config/function.inc.php");

class CSendMail extends PageBase
{
	/* 加载页面 */
	function OnPageLoad(){
		include("./class/template.inc");
		
		$tpl = new Template("./ui/");
		
/*		if( CheckSendMail() ){
			// 显示发送邮件界面
			$tpl->set_file("main", "sendemail-b.html");
			$tpl->pparse("mains", "main");
			return;
		} */
		// 显示普通界面
		$tpl->set_file("main", "sendemail.html");
		$tpl->set_block("main", "group_list", "s_group_list");
		$this->mysql = new QuickMySQL();
		$res = $this->mysql->Query("select sname,tname from t_list_user");
		while( $row = mysql_fetch_row($res) ){
			$tpl->set_var("tb", substr($row[1], 7));
			$tpl->set_var("name", $row[0]);
			$tpl->parse("s_group_list", "group_list", true);
		}
		
		$tpl->pparse("mains", "main");
		
	}
	/* 处理请求 */
	function OnRequest(){
		echo "<meta http-equiv=\"content-type\" content=\"text/html;charset=uft-8\">";
		
		$users = array("vm" => "t_user_vm", "qq" => "t_user_qq");
		$title = $_POST['title'];
		$body = eregi_replace("[\](.)",'\\1',$_POST['sendemail_preview']);//base64_encode($_POST['sendemail_preview']);
		$body = str_replace("'", "''", $body);
		$user = "";
		foreach( $users as $ut => $tt ){
			if( !isset($_POST["utype_" . $ut]) )
				continue;
			if( $ut != $_POST["utype_" . $ut])
				continue;
			if( "" != $user ) $user .= ";";
			$user .= $tt;
		}
		if("" == $user){
			echo "<script language='javascript'>alert('发送的用户为空'); location = 'sendemail.php'</script>";
			return;
		}
		// 添加到发送队列
		$sql = "insert into t_sendmail_queue(sm_subject,sm_to,sm_body) values("
			. "'" . str_replace("'", "''", $title) . "'"
			. ",'" . str_replace("'", "''", $user) . "'"
			. ", '{$body}')";
		if( !QuickMySQL::quickExecute($sql) ){
			echo "<script language='javascript'>alert('添加到发送队列失败'); location = 'sendemail.php'</script>";
			return;
		}
		// 启动新线程
		$fp = fsockopen($_SERVER['SERVER_ADDR'], $_SERVER['SERVER_PORT'], $errno, $error);
		if( $fp ){
			fputs($fp, "GET /class/sendemail-s.php\r\n");
			fputs($fp, "Host: {$_SERVER['HTTP_HOST']}\r\n\r\n");
			fclose($fp);
			echo "<script language='javascript'>location = 'sendemail.php'</script>";
			sleep(1); // 等等进程启动
		} else {
			echo "<script language='javascript'>alert('启动发送邮件失败'); location = 'sendemail.php'</script>";
		}
	}
}

$cc = new CSendMail();
?>